<template>
  <el-row>
    <el-col :span="24">
      <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="110px">
        <Portlet title="公司信息">
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="公司名称" prop="name" :rules="[
                    {required: true, message: '公司名称必须', trigger: 'blur'}
                  ]">
                <el-input v-model="model.name"></el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="总经理" prop="manager" :rules="[
                    {required: true, message: '总经理必须', trigger: 'blur'}
                  ]">
                <el-input v-model="model.manager"></el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="统一社会代码" prop="communityCode" :rules="[
                    {required: true, message: '统一社会代码必须', trigger: 'blur'}
                  ]">
                <el-input v-model="model.communityCode"></el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="公司法人" prop="legalPerson" :rules="[
                  {required: true, message: '公司法人必须', trigger: 'blur'},
                ]">
                <el-input v-model="model.legalPerson"></el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="注册日期" prop="registeDate" :rules="[
                  {required: true, message: '注册日期必须', trigger: 'change'},
                ]">
                <el-date-picker type="date" value-format="yyyy-MM-dd" v-model="model.registeDate"></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="办公地址" prop="addressArr" :rules="[
                  {required: true, message: '办公地址必须', trigger: 'change', type: 'array'},
                ]">
                <CascadeAddress :level="3" v-model="model.addressArr"></CascadeAddress>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="办公详情地址" prop="detailAddress" :rules="[
                  {required: true, message: '办公详情地址必须', trigger: 'blur'},
                ]">
                <el-input type="textarea" v-model="model.detailAddress"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="LOGO" prop="imageArr" :rules="[
                  {required: true, message: 'LOGO必须', trigger: 'change', type: 'array'},
                ]">
                <UploadImage v-model="model.imageArr" :max="1" :formData="{group: id || 'company'}"></UploadImage>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="公司域名" prop="url" :rules="[
              {validator: isEnglish, message: '只能是英文字母', trigger: 'blur'}
              ]">
                <el-input v-model="model.url" placeholder="例如：cd"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label=".sp.jjtvip.com"></el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15" v-for="(item, index) in model.phoneArr" :key="index">
            <!--新加 公司电话-->
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="公司服务热线" :prop="'phoneArr.' + index + '.phone'"
                            :rules="[
                     {required: true, message: '公司电话号码必须', trigger: 'blur'},
                     {validator: isPhoneOrTel, message: '电话格式不正确', trigger: 'blur'}
                  ]">
                <el-input v-model="item.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-button @click="delFee(model.phoneArr, index)">删除</el-button>
              <el-button @click="addFee" type="primary">添加</el-button>
            </el-col>
            <!--<div class="col-xs-3" v-if="index == 0"><span>（最多添加4个电话号码）</span></div>-->
          </el-row>
        </Portlet>

        <Portlet title="分配账号">
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="账号姓名:" prop="userId" :rules="[
                      {required: true, message: '账号姓名必须', trigger: 'change'}
                    ]">
                <el-select
                  v-model="model.userId"
                  filterable
                  clearable
                  placeholder="请输入关键词"
                  remote
                  :remote-method="remoteQuery"
                  :loading="cargoOwnerLoading">
                  <el-option
                    v-for="item in cargoOwnerArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label-width="120px" label="绑定登录手机号:">
                <el-input :disabled="true" :value="userPhone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label-width="120px" prop="position" label="账号岗位:" :rules="[
                      {required: true, message: '账号岗位必填', trigger: 'change'}
                    ]">
                <el-input v-model="model.position"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet title="业务模式">
          <el-row :gutter="15">
            <el-col :span="24">
              <el-form-item label-width="0" prop="businessModeCode" :rules="[
                      {required: true, message: '业务模式必须', trigger: 'change'}
                    ]">
                <el-radio-group v-model="model.businessModeCode">
                  <el-radio v-for="item in businessTypes" :key="item.value" :label="item.value">{{ item.text }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

        </Portlet>

        <Portlet>
          <el-row :gutter="15">
            <el-col :span="24" class="text-center">
              <div class="col-xs-4 col-xs-offset-4">
                <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">{{ id ? '保存' : '新增' }}</el-button>
              </div>
            </el-col>
          </el-row>
        </Portlet>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import {copy, dotData, alert, confirm} from '@/utils'
import {httpSuccessPost, httpGetResponse} from '@/utils/ajax'
import {getCompanyBusinessType} from '@/utils/selectOptions'
import {filterDataBaseDictionary, unixTimestampFilter} from '@/filters'
import {isFormatNumber, isPhone, isPhoneOrTel, isEnglish} from '@/utils/validate'

import L from 'lodash'
export default {
  filters: {
    filterDataBaseDictionary
  },
  data() {
    return {
      id: this.$route.params.id,
      routeName: this.$route.name,
      loading: false,
      cargoOwnerLoading: false,
      model: {
        name: '',
        manager: '',
        communityCode: '',
        legalPerson: '',
        registeDate: '',
        detailAddress: '',
        position: '',
        userId: '',
        addressArr: [],
        imageArr: [],
        phoneArr: [
          { phone: '' }
        ],
        businessModeCode: ''
      },
      userIdMap: new Map(),
      cargoOwnerArr: [],
      businessTypes: []
    }
  },
  computed: {
    userPhone() {
      let temp = this.userIdMap.get(this.model.userId)
      if (temp) {
        return dotData(temp, 'phone')
      }
      return ''
    }
  },
  created() {
    // 获取详情信息，并回填
    if (this.id) {
      httpGetResponse('/ms-warehouse-order/company/getCompanyById', {companyId: this.id}).then(response => {
        if (!response.data) {
          return
        }
        this.model.name = dotData(response, 'data.name')
        this.model.manager = dotData(response, 'data.manager')
        this.model.communityCode = dotData(response, 'data.communityCode')
        this.model.legalPerson = dotData(response, 'data.legalPerson')
        this.model.registeDate = dotData(response, 'data.registeDate') ? unixTimestampFilter(dotData(response, 'data.registeDate'), 'YYYY-MM-DD') : ''
        this.model.detailAddress = dotData(response, 'data.detailAddress')
        this.model.userId = dotData(response, 'data.userId')
        this.model.businessModeCode = dotData(response, 'data.businessModeCode')
        let _url = dotData(response, 'data.url')
        if (_url) {
          this.model.url = _url.slice(0, _url.lastIndexOf('.sp.jjtvip.com'))
        }
        // this.model.position = dotData(response, 'data.position') // 修改详情之前的 回填岗位
        if (this.model.userId) {
          this.cargoOwnerArr = [
            {
              value: this.model.userId,
              text: dotData(response, 'data.userName')
            }
          ]
          this.userIdMap.set(this.model.userId, {phone: dotData(response, 'data.userPhone'), position: dotData(response, 'data.position')})
        }
        // 回填地址数据
        let addressArr = []
        if (dotData(response, 'data.provinceNo')) {
          addressArr.push(dotData(response, 'data.provinceNo'))
          if (dotData(response, 'data.cityNo')) {
            addressArr.push(dotData(response, 'data.cityNo'))
            if (dotData(response, 'data.districtNo')) {
              addressArr.push(dotData(response, 'data.districtNo'))
            }
          }
        }
        this.model.addressArr = addressArr
        // logo 数据
        if (dotData(response, 'data.logo')) {
          this.model.imageArr = [dotData(response, 'data.logo')]
        }
        // 回填多个公司电话：将字符串处理成数组
        let backPhones = dotData(response, 'data.serviceHotline')
        if (backPhones && typeof backPhones === 'string') {
          let backPhoneArr = backPhones.split(',')
          this.model.phoneArr = []
          for (let i in backPhoneArr) {
            this.model.phoneArr.push({phone: backPhoneArr[i]})
          }
        }
      })
    }
    // 公司业务类型
    getCompanyBusinessType().then(arr => {
      this.businessTypes = arr
    })
  },
  watch: {
    // 监听手动重新选择了账号姓名，useId对象里面有职位就回填，没有就清空
    'model.userId'(val, oldVal) {
      let temp = this.userIdMap.get(this.model.userId)
      let positionVal = dotData(temp, 'position')
      if (positionVal) { // 若 手动重新选择userId，且里面有岗位，则回填到modal,反之，清空position
        this.model.position = positionVal
      } else {
        this.model.position = ''
      }
    }
  },
  methods: {
    isFormatNumber,
    isPhone,
    // isPhoneAlias,
    isPhoneOrTel,
    isEnglish,
    httpPost(url) {
      let data = copy(this.model, true)
      if (this.id) {
        data.id = this.id
      }
      // 处理地址
      data.provinceNo = dotData(data.addressArr, '[0]')
      data.cityNo = dotData(data.addressArr, '[1]')
      data.districtNo = dotData(data.addressArr, '[2]')
      delete data.addressArr
      // 处理图片
      data.logo = dotData(data.imageArr, '[0]')
      delete data.imageArr
      // 处理电话号码
      if (Array.isArray(data.phoneArr)) {
        let tempArr = []
        data.phoneArr.forEach(v => {
          tempArr.push(v.phone)
        })
        data.serviceHotline = tempArr.join(',')
      }
      data.url = data.url + '.sp.jjtvip.com'
      delete data.phoneArr
      return httpSuccessPost(url, data)
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.loading = true
        let title = this.id ? '编辑成功' : '新增成功'
        let url = this.id ? '/ms-warehouse-order/company/updateCompany' : '/ms-warehouse-order/company/saveCompany'
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm(title, title, {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).finally(_ => {
              this.$router.push({path: '/ss-oms/basic-data/company/index'})
              this.resetFields()
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      try {
        this.$refs.elForm.resetFields()
      } catch (err) {
        console.log(err)
      }
    },
    // 后端搜索
    remoteQuery(query) {
      this.cargoOwnerLoading = true
      this.remoteMethod(query, this)
    },
    // 后端模糊搜索 函数防抖
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      httpGetResponse('/ms-warehouse-order/user/getUserByName', {name: query}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            _this.userIdMap.clear()
            data.forEach((v, k) => {
              tempArr.push({
                text: v.name,
                value: v.userId
              })
              _this.userIdMap.set(v.userId, {phone: v.phone, position: v.position}) // 多加一个账号岗位
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000),
    // 新加一行
    addFee() {
      if (this.model.phoneArr.length <= 3) {
        this.model.phoneArr.push({})
      }
    },
    // 删除一行
    delFee(arr, index) {
      if (arr.length <= 1) {
        return
      }
      arr.splice(index, 1)
    }
  }
}
</script>
